package android.magical;

import java.util.ArrayList;
import java.util.List;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothFragment extends ListFragment implements OnClickListener {
	private MagiCalBT magicBT;
	private BluetoothAdapter bluetooth;
	private TextView scanBTbutton;
	private String TAG = "BluetoothFragment";
	List<String> devicesDiscoveredList = new ArrayList<String>();
	private static ArrayAdapter<String> deviceListAdapter;
	private static BluetoothDevice bd;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View v = inflater.inflate(R.layout.devicelist, container, false);

		bluetooth = BluetoothAdapter.getDefaultAdapter();
		magicBT = ((MainActivity) getActivity()).getMagicalBT();

		// initial arrayadapter
		scanBTbutton = (TextView) v.findViewById(android.R.id.empty);
		scanBTbutton.setOnClickListener(this);

		deviceListAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, devicesDiscoveredList);

		// link the arrayadapter to the device list
		setListAdapter(deviceListAdapter);

		return v;
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void onPause() {
		super.onPause();
		if (bluetooth.isDiscovering()) {

			getActivity().unregisterReceiver(DeviceSearching);
			bluetooth.cancelDiscovery();
		}
	}

	public void onClick(View v) {// click activities for different buttons
		switch (v.getId()) {

		case android.R.id.empty:// for the BT device scan button

			if (bluetooth == null) {
				Log.i(TAG, "Bluetooth not available");
				return;

			} else {
				Log.i(TAG, "Scanning for BT device");
				scanBTbutton.setClickable(false);
				if (bluetooth.getState() == BluetoothAdapter.STATE_OFF) {

					Toast.makeText(getActivity(),
							"Please turn on bluetooth first", Toast.LENGTH_LONG)
							.show();
					return;
				}

				// register intent to get result when we found a device,
				// ACTION_FOUND
				IntentFilter intent = new IntentFilter();

				// Register action ACTION_FOUND, so that we can execute
				// some code each time the intent found a bluetooth device
				intent.addAction(BluetoothDevice.ACTION_FOUND);

				// Register action ACTION_DISCOVERY_FINISHED
				intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

				// Register intent so that BroadcastReceiver will be called
				// when it matches intent filters
				getActivity().registerReceiver(DeviceSearching, intent);

				// setTitle("Device bluetooth MAC：" + bluetooth.getAddress());

				devicesDiscoveredList.clear();

				//
				if (bluetooth.isDiscovering()) {
					bluetooth.cancelDiscovery();
				}
				// start discovery, the Broadcastreceiver will be notified
				// if it matches any of the intent filter above
				bluetooth.startDiscovery();

			}
			break;

		default:
			break;

		}
	}

	public static BluetoothDevice getBTDevice() {
		Log.i("BluetoothFragment", "bd string " + bd.toString());
		return bd;
	}

	@Override
	public void onListItemClick(ListView arg0, View view, int arg2, long arg3) {
		
		String info = ((TextView) view).getText().toString();
		
		Toast.makeText(getActivity(), "Connecting.....", Toast.LENGTH_LONG)
				.show();
		
		// The last 17 digit of the info is the device MAC address
		final int macaddresslength = 17;
		String address = info.substring(info.length() - macaddresslength);// extract
																			// MAC
																			// from
																			// string
		Log.i(TAG, address);

		// display clicked device MAC address using Toast
		//Toast.makeText(getActivity(), address, Toast.LENGTH_LONG).show();

		// setup bluetooth device object using the MAC address we just got
		BluetoothDevice device = bluetooth.getRemoteDevice(address);
		bd = device;

		// Attempt to connect to the device

		magicBT.start(device);


	}

	// BroadcastReceiver for discovering device
	private BroadcastReceiver DeviceSearching = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
			if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {// when
																			// discovery
																			// action
																			// is
																			// complete
				
				Log.i(TAG, "discovery finished");
				
				scanBTbutton.setEnabled(true);
				
				getActivity().unregisterReceiver(DeviceSearching);
				
			} else if (BluetoothAdapter.ACTION_REQUEST_ENABLE.equals(action)) {
				Log.i(TAG, "enabled");
/*			} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
				// Log.i(TAG,"bond state change");
*/			} else {// for all other intent filters

				Bundle b = intent.getExtras();

				Object[] objname = b.keySet().toArray();

				// display all the data receive on logcat

				for (int i = 0; i < objname.length; i++) {

					String keyName = objname[i].toString();

					Log.i(TAG + "|" + keyName, String.valueOf(b.get(keyName)));

				}

				// When the broadcastreceiver found a new device

				if (BluetoothDevice.ACTION_FOUND.equals(action)) {

					// pull device data out from the intent

					BluetoothDevice device = intent
							.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

					String str = "" + device.getName() + "|"
							+ device.getAddress();

					Log.i(TAG, "Found new device " + (str));

					if (devicesDiscoveredList.indexOf(str) == -1) {// aviod
																	// repeating
																	// the same
																	// address

						devicesDiscoveredList.add(str); // put the new
														// device(including the
														// device name) we found
														// on the list

						Log.i(TAG, str);

					}

					// refresh the list in the array adapter

					deviceListAdapter.notifyDataSetChanged();

				}
			}

		}

	};

}
